<html>
    <head>
        <title>Products</title>
        <link href="style.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>
        <div id="page">
            <div id="logo">
                <h1><a href="#">Products</a></h1>
                <div class='div'>
                    &nbsp
                </div>
                <br/>
                <form onsubmit="handleSubmit(); return false;">
                    <div class='field'>
                        UPC:<input type='text' id='upc' name='upc' value='upc'>
                    </div>
                    <div class='field'>
                        Description:<input class='field' type='text' id='description' name='description'>
                    </div>
                    <div class='field'>
                        Brand:<input type='text' id='brand' name='brand'>
                    </div>
                    <div class='field'>
                        Model:<input type='text' id='model' name='model'>
                    </div>
                    <div class='field'>
                        Type:<a href='./productTypes.html'>[+]</a>
                        <span id='ptypespan' name='ptypespan'></span>
                    </div>
                    <div class='field'>
                        Quantity:<input type='button' style='width:18px;' id='delqty' onclick='AddOne("quantity",-1);' value='-' /><input type='button' id='addqty' value='+' style='width:18px;'  onclick='AddOne("quantity",1);'/><input type='text' style='width:50px;' id='quantity' name='quantity'>
                    </div>
                    <div class='field'>
                        Ordered:<input type='button' style='width:18px;' id='delqty' onclick='AddOne("ordered",-1);' value='-' /><input type='button' id='addqty' value='+' style='width:18px;'  onclick='AddOne("ordered",1);'/><input type='text' style='width:50px;' id='ordered' name='ordered'>
                    </div>
                    <div class='field'>
                        Cost:<input type='text' id='cost' name='cost'>
                    </div>
                    <div class='field'>
                        Price:<input type='text' id='price' name='price'>
                    </div>
					<div class='field'>
                       <input type='button' value='Save' onclick='Save()'/>
                    </div>
                    <br/>
                    <div class='field'>
                        Search?:<input type='text'  id='searcht' name='searcht'></div>
						<div class='field'>	
                    <input type='button' class='buttons' value='Search' onclick='Search(getElementById("searcht").value);'/></div>
            
                    <div class='field'>
                        Load?:<input type='text' id='pid' name='pid'></div>
						<div class='field'>
                    <input type='button' value='Load' onclick='Load()'/>
					</div>
                </form><span id="status">&nbsp;</span>
                <!-- ====================================== -->
                <!-- End HTML code.  Begin JavaScript code. -->
                <script type="text/javascript" src="gears_init.js">
                </script>
                <script type="text/javascript" src="sample.js">
                </script>
                <script>
                    
                    var db;
                    init();
                   var query = location.search;
                   var itemid = query.substring(query.indexOf("id=") + 3, query.length);
                    
                     if(itemid != '')
                     {
                     	var pidT = getElementById('pid');
                     	pidT.value = itemid;
                     	Load();
                     }
                     
                    // Open this page's local database.
                    function init(){
                        var success = false;
                        
                        if (window.google && google.gears) {
                            try {
                                db = google.gears.factory.create('beta.database');
                                
                                if (db) {
                                    db.open('database-demo');
                                    db.execute('create table if not exists Product' +
                                    ' (id int primarykey,' +
                                    ' UPC text,' +
                                    ' description text,' +
                                    ' brand text,' +
                                    ' model text,' +
                                    ' type text,' +
                                    ' quantity real,' +
                                    ' ordered real,' +
                                    ' cost real,' +
                                    ' price text' +
                                    ')');
                                    
                                    success = true;
                                    // Initialize the UI at startup.
                                    
                                    displayRecentPhrases();
                                    loadProductTypes('');
                                }
                                
                            } 
                            catch (ex) {
                                setError('Could not create database: ' + ex.message);
                                alert('Could not create database: ' + ex.message);
                            }
                        }
                        
                        // Enable or disable UI elements
                        
                        var inputs = document.forms[0].elements;
                        for (var i = 0, el; el = inputs[i]; i++) {
                            el.disabled = !success;
                        }
                        
                    }
                    
                    function Save(){
                        if (!google.gears.factory || !db) {
                            return;
                        }
                        
                        var upcT = getElementById('upc');
                        var descriptionT = getElementById('description');
                        var brandT = getElementById('brand');
                        var modelT = getElementById('model');
                        var typeT = getElementById('type');
                        var quantityT = getElementById('quantity');
                        var orderedT = getElementById('ordered');
                        var costT = getElementById('cost');
                        var priceT = getElementById('price');
                        
                        var upc = upcT.value;
                        var description = descriptionT.value;
                        var brand = brandT.value;
                        var model = modelT.value;
                        var type = typeT.value;
                        var quantity = quantityT.value;
                        var ordered = orderedT.value;
                        var cost = costT.value;
                        var price = priceT.value;
                        var currTime = new Date().getTime();
                        
                        //get the new id
                        var rs = db.execute('select max(id)+1 as pid from product');
                        var newid = 0;
                        while (rs.isValidRow()) {
                            newid = rs.field(0);
                        }
                        
                        // Insert the new item.
                        // The Gears database automatically escapes/unescapes inserted values.
                        db.execute('insert into Product (id, upc, description, brand, model, type, quantity, ordered, cost, price) values (?,?,?,?,?,?,?,?,?,?)', [upc, description, brand, model, type, quantity, ordered, cost, price]);
                        alert('Product added.');
                        // Update the UI.
                        //elm.value = '';
                        //displayRecentPhrases();
                    }
                    
                    
                    function displayRecentPhrases(){
                        var recentPhrases = ['', '', ''];
                        
                        // Get the 3 most recent entries. Delete any others.
                        var rs = db.execute('select * from product order by 1 desc');
                        var index = 0;
                        while (rs.isValidRow()) {
                            if (index < 3) {
                                recentPhrases[index] = rs.field(0) + '-' + rs.field(1);
                            }
                            else {
                                alert('Nothing');//db.execute('delete from customer where Timestamp=?', [rs.field(1)]);
                            }
                            ++index;
                            rs.next();
                        }
                        rs.close();
                        
                        var status = getElementById('status');
                        status.innerHTML = '';
                        for (var i = 0; i < recentPhrases.length; ++i) {
                            var id = 'phrase' + i;
                            status.innerHTML += '<span id="' + id + '"></span><br>';
                            var bullet = '(' + (i + 1) + ') ';
                            setTextContent(getElementById(id), bullet + recentPhrases[i]);
                        }
                    }
                    
                    function Search(search){
                        var recentPhrases = ['', '', ''];
                        var query = 'select * from product where UPC like "' + search + '%"';
                        query += ' OR description like "' + search + '%"';
                        query += ' OR brand like "' + search + '%"';
                        query += ' OR model like "' + search + '%"';
                        //query += ' OR [type] like "' + search+ '%"';
                        
                        //alert(query);
                        
                        var status = getElementById('status');
                        status.innerHTML = '';//'Searching...' ;
                        var rs = db.execute(query);
                        var index = 0;
                        while (rs.isValidRow()) {
                            if (index < 3) {
                                recentPhrases[index] = rs.field(1) + '-' + rs.field(2);
                            }
                            ++index;
                            rs.next();
                        }
                        rs.close();
                        
                        
                        for (var i = 0; i < recentPhrases.length; ++i) {
                            var id = 'phrase' + i;
                            status.innerHTML += '<span id="' + id + '"></span><br>';
                            var bullet = '(' + (i + 1) + ')';
                            setTextContent(getElementById(id), bullet + recentPhrases[i]);
                        }
                    }
                    
                    function Load(){
                        var pidT = getElementById('pid');
                        var id = pidT.value;
                        
                        var rs = db.execute('select * from product where id=' + id);
                        var index = 0;
                        
                        var upcT = getElementById('upc');
                        var descriptionT = getElementById('description');
                        var brandT = getElementById('brand');
                        var modelT = getElementById('model');
                        var typeT = getElementById('type');
                        var quantityT = getElementById('quantity');
                        var orderedT = getElementById('ordered');
                        var costT = getElementById('cost');
                        var priceT = getElementById('price');
                        
                        while (rs.isValidRow()) {
                        
                            upcT.value = rs.field(1);
                            descriptionT.value = rs.field(2);
                            brandT.value = rs.field(3);
                            modelT.value = rs.field(4);
                            quantityT.value = rs.field(6);
                            orderedT.value = rs.field(7);
                            costT.value = rs.field(8);
                            priceT.value = rs.field(9);
                            loadProductTypes(rs.field(5));
                            
                            rs.next();
                        }
                        rs.close();
                    }
                    
                    function loadProductTypes(sel){
                        var rs = db.execute('select * from ProductType order by 2 desc');
                        var index = 0;
                        var ptypespan = getElementById('ptypespan');
                        var itext = '';
                        itext += '<select name="producttype">';
                        while (rs.isValidRow()) {
                            itext += '<option value="' + rs.field(0) + '"';
                            if (sel == rs.field(0)) 
                                itext += ' selected ';
                            itext += '>' + rs.field(1) + '</option>';
                            rs.next();
                        }
                        rs.close();
                        itext += '</select>';
                        //alert(itext);
                        ptypespan.innerHTML = itext;
                        
                    }
                    
                    function AddOne(control, amount){
                        var pcontrol = getElementById(control);
                        var amount1 = new Number(amount);
                        var amount2 = new Number(pcontrol.value);
                        var result = amount1 + amount2;
                        
                        pcontrol.value = result;
                    }
                    
                </script>
                </body>
            </html>
